/**
 * @author chuzhixin 1204505056@qq.com （不想保留author可删除）
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from 'vue'
import {
  getUserInfo,
  login,
  logout,
} from '@/api/user'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
  getEmpInfo,
  setEmpInfo
} from '@/utils/accessToken'
import { resetRouter } from '@/router'
import router from '@/router'
import { tokenName, empIdName } from '@/config'
import store from '..'
import { indexOf } from 'lodash'
const state = {
  accessToken: getAccessToken(),
  username: '',
  avatar: '',
  permissions: [],
  user: {},
  //终端类型
  terminalType: 'web',
  curEmp: getEmpInfo(),
  employees: []
}
const getters = {
  accessToken: (state) => state.accessToken,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  permissions: (state) => state.permissions,
  user: (state) => state.user,
  terminalType: (state) => state.terminalType,
  employees: (state) => state.employees,
  curEmp: (state) => state.curEmp
}
const mutations = {
  setAccessToken (state, accessToken) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  setUsername (state, username) {
    state.username = username
  },
  setAvatar (state, avatar) {
    if (!avatar) {
      avatar = require('@/assets/user.png')
    }
    state.avatar = avatar
  },
  setPermissions (state, permissions) {
    state.permissions = permissions
  },
  setUser (state, user) {
    state.user = user
    if (!user) {
      state.employees = []
    }
  },
  setTerminalType (state, terminalType) {
    state.terminalType = terminalType
  },
  setEmployees (state, emps) {
    state.employees = emps
    if (!emps || emps.length == 0) {
      state.curEmp = null
      setEmpInfo(state.curEmp)
    }
    if (!state.curEmp && emps && emps.length > 0) {
      state.curEmp = emps[0]
      setEmpInfo(state.curEmp)
    }
  },
  changeCurEmp (state, employee) {
    state.curEmp = employee
    setEmpInfo(state.curEmp)
    store.dispatch('user/getUserInfo')
    location.reload()
  }
}
const actions = {
  setPermissions ({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login ({ commit }, userInfo) {
    const data = await login(userInfo)
    if (data.success) {
      const accessToken = data.data.user.USR_Token
      const employees = data.data.employees
      commit('setAccessToken', accessToken)
      commit('setEmployees', employees)
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
            ? '上午好'
            : hour <= 13
              ? '中午好'
              : hour < 18
                ? '下午好'
                : '晚上好'
      Vue.prototype.$baseNotify(`欢迎登录${data.data.user.USR_Name}`, `${thisTime}！`)
    } else {
      Vue.prototype.$baseMessage(
        `登录接口异常，未正确返回${tokenName}...`,
        'error'
      )
    }
  },
  async getUserInfo ({ commit, state }) {
    var req = {
      [tokenName]: state.accessToken,
      [empIdName]: state.curEmp.EMP_ID
    }
    const { data } = await getUserInfo(req)
    if (!data) {
      Vue.prototype.$baseMessage('验证失败，请重新登录...', 'error')
      return false
    }
    let user = data.user
    let permissions = data.permissions
    let employees = data.employees
    let username = user.USR_Name
    if (permissions && username && Array.isArray(permissions) && user) {
      commit('setPermissions', permissions)
      commit('setUsername', username)
      commit('setEmployees', employees)
      commit('setUser', user)
      return permissions
    } else {
      Vue.prototype.$baseMessage('用户信息接口异常', 'error')
      return false
    }
  },
  async logout ({ dispatch }) {
    await logout(state.accessToken)
    await dispatch('resetAccessToken')
    await resetRouter()
  },
  resetAccessToken ({ commit }) {
    commit('setEmployees', [])
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
